import { OptionToolbar } from '@/components/Toolbar';
import { getMain } from '@/services/zhirong/visualAnalysis';
import ProCard from '@ant-design/pro-card';
import Graphin, { Behaviors } from '@antv/graphin';
import { useRequest } from '@umijs/hooks';
import { Popover, Select, Tag, InputNumber } from 'antd';
import { useEffect, useRef, useState } from 'react';
// import { OptionToolbarTwo } from '@/components/Toolbar';
import { Collapse } from 'antd';
import VisualAnalysisLayout from '../VisualAnalysisLayout ';
import classes from './index.module.css';
import { CloseOutlined } from '@ant-design/icons'
import { KeepAlive } from 'umi'
import { P } from '@antv/g2plot';

const { Panel } = Collapse;
const { Option } = Select;
const { ZoomCanvas, DragNodeWithForce, FitView } = Behaviors;
const layout = {
  type: 'gForce',
  rankdir: 'BT',
  preventOverlap: true,
  clustering: true,
  clusterNodeStrength: -5,
  clusterEdgeDistance: 500,
  clusterNodeSize: 10,
  clusterFociStrength: 1.2,
  nodeSpacing: 10,
};

const MainGraph = () => {
  const [topKVisible, setTopKVisible] = useState(false);
  // topK的取值
  const [k, setK] = useState();
  // 存储topK的值以确保所有的点都在
  const [topK, setTopK] = useState();
  const [search, setSearch] = useState({ eid: 'fa65c5e6-c5e9-11e7-a96b-00163e1254b5' });
  // 存储最原始的graph
  const [initGraph, setInitGraph] = useState();
  // 用于时间演化的参数
  const [date, setDate] = useState('2022-01-01');
  const [graph, setGraph] = useState({
    nodes: [],
    edges: [],
  });
  // 节点数据
  const [data, setData] = useState();
  const graphRef = useRef(null);
  const options = [
    {
      label: '度中心性',
      value: 'degree_centrality',
      color: 'orange',
    },
    {
      label: '特征向量中心性',
      value: 'eigenvector_centrality',
      color: 'green',
    },
    {
      label: '接近中心性',
      value: 'closeness_centrality',
      color: 'blue',
    },
    {
      label: '中介中心性',
      value: 'betweenness_centrality',
      color: 'purple',
    },
  ];

  //
  const { run, loading: loadingGraph } = useRequest(getMain, {

    onSuccess: (res) => {
      //有返回值
      console.log('我是关键公司分析的结果>>>', res);
      const { data, h_average, h_max } = res.data;
      const { nodes, links } = data;
      console.log("nodes出来了吗", nodes);
      // 返回的是option对应的二维数组
      let topK = options?.map((option) => {
        return {
          [option.value]: Object?.entries(res.data[option.value]).sort((a, b) => b[1] - a[1]),
          // [option.value]: Object?.entries(data[option.value]).sort((a, b) => b[1] - a[1]),
        };
      });
      console.log("topK出来了吗", topK)

      // topK的格式为 [{ option.value: [[]] } ]
      const edges = [];
      const ids = nodes?.map((node) => node.id);
      links?.forEach((link) => {
        if (ids.indexOf(link.source) !== -1 && ids.indexOf(link.target) !== -1) {
          edges.push(link);
        }
      });
      edges?.forEach((edge) => {
        edge.style = {
          keyshape: {
            fill: '#999',
            stroke: '#999',
            lineWidth: 0.7,
            type: edge.target === edge.source ? 'loop' : 'string',
          },
        };
      });
      nodes?.forEach((node) => {
        if (node.backbonenode === 'yes') {
          node.style = {
            keyshape: {
              stroke: 'red',
              fill: 'red',
              size: 25,
            },
            label: {
              value: node.name,
            },
          };
        } else {
          node.style = {
            keyshape: {
              size: 18,
            },
          };
        }
      });

      console.log('nodes', nodes);
      setGraph({ nodes, edges, h_average, h_max, topK });
      setInitGraph({ nodes, edges, h_average, h_max, topK })
      setTopK(topK);
      // setGraph({ nodes, edges, });
      setData(nodes);
    },
  });

  useEffect(() => {
    if (search.eid) {
      run({
        entityA: search.eid,
        date: date
      });
    }
    console.log('searchgraph', graph);
  }, [search, run]);

  useEffect(() => {
    console.log('graph', graph);
  }, [graph]);

  useEffect(() => {
    console.log('topK执行啦');
    if (topK) {
      let newTopK = topK.map((item) => {
        // 为了不跟options的value混淆，这里value多加了一个e
        // 通过已经排序好的topK，从中获取前k个节点进行高亮
        let valuee = Object.keys(item)[0];
        return {
          [valuee]: item[valuee].slice(0, k),
        };
      });
      setGraph({ ...initGraph, topK: newTopK });
    }
  }, [k]);

  const [loading, setLoading] = useState(false);
  const refresh = () => {
    setTopKVisible(false);
    setLoading(true);
    setTimeout(() => setLoading(false), 0);
  };
  const filter = () => {
    setTopKVisible(!topKVisible);
  };
  const handleTimeChange = (time) => {
    let { edges } = initGraph;
    switch (time) {
      case '2021':
        edges = edges.filter((edge) => edge.value > 0.5);
        break;
      case '2020':
        edges = edges.filter((edge) => edge.value > 0.2 && edge.value <= 0.5);
        break;
      case "2019":
        edges = edges.filter((edge) => edge.value <= 0.2 && edge.value > 0.0);
        break;
      default:
        edges = edges;
        break;
    }
    setGraph({ ...initGraph, edges });
    const date = time + '-01-01';
    setDate(date);
    console.log("改变时间值", date);
  };
  const hide = () => {
    setTopKVisible(false)
  }
  const handleSelectChange = (key) => {
    console.log('改变k值', Number.parseInt(key));
    setK(Number.parseInt(key));
  };
  const onTagClick = (e) => {
    //topK的值是二维数组，这是将其变成一维数组
    const ids = Object.values(graph.topK[e.target.id])[0];
    ids.forEach((id) => {
      const node = graphRef.current.graph.find('node', (n) => {
        return id[0] === n.getModel().id;
      });
      try {
        const model = node.getModel();
        graphRef.current.graph.updateItem(node, {
          ...model,
          style: {
            keyshape: {
              stroke: options[e.target.id].color,
              fill: options[e.target.id].color,
              size: 25,
            },
            label: {
              value: `${model.name} \n ${id[1].toFixed(3)}`,
            },
          },
        });
      } catch (error) {
        console.log('出错啦:', error);
      }
    });
  };

  return (
    <VisualAnalysisLayout onSubmit={setSearch} title="关键公司分析">
      <ProCard
        bodyStyle={{ margin: '0.5em', padding: 0 }}
        style={{ height: '70px', width: '100%', borderRadius: '8px' }}
      >
        {
          graph.nodes.length ? (<div className={classes.infoPanel}>
            <div className={classes.infoGut}>企业总数: {graph.nodes?.length} </div>
            <div className={classes.infoGut}>平均控制度: {Number(graph.h_average)?.toFixed(2)} </div>
            <div className={classes.infoGut}>最大控制度: {Number(graph.h_max)?.toFixed(2)}</div>
            <div className={classes.infoGut}>
              请选择演化时间:&nbsp;
              <Select
                style={{
                  width: 120,
                }}
                size="small"
                defaultValue="2022"
                onChange={handleTimeChange}
              >
                <Option value="2022">2022</Option>
                <Option value="2021">2021</Option>
                <Option value="2020">2020</Option>
                <Option value="2019">2019</Option>
              </Select>
            </div>
          </div>) : <div className={classes.infoPanel}></div>

        }
        <div className={classes.infoPanel}>
          {options.map((option, index) => {
            return (
              <div key={option.value} style={{ marginBottom: '10px', cursor: 'pointer' }}>
                <div className={classes.box}>
                  <Tag color={option.color} onClick={onTagClick} id={index}>
                    {option.label}
                  </Tag>
                </div>
              </div>
            );
          })}
        </div>
      </ProCard>
      <ProCard
        loading={loading || loadingGraph}
        style={{ height: '100vh', width: '100%', borderRadius: '8px' }}
      >
        {/* <KeepAlive> */}
        <Graphin
          data={graph}
          layout={layout}
          FitView="true"
          fitcenter
          ref={graphRef}
          style={{ height: '100%', width: '100%' }}
        >
          <ZoomCanvas />
          <Popover
            content={
              <div>
                <div>
                  显示Top
                  <InputNumber step={5} min={0} defaultValue={5} onChange={handleSelectChange} />
                  节点
                </div>

              </div>
            }
            title={
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <div>筛选</div>
                <a onClick={hide}><CloseOutlined style={{ fontSize: "14px", color: "#aaa" }} /></a>
              </div>
            }
            trigger="manual"
            visible={topKVisible}
            destroyTooltipOnHide
          // onVisibleChange={handleVisibleChange}
          >
            <OptionToolbar direction={'horizontal'} filter={filter} refresh={refresh} />
          </Popover>
          <DragNodeWithForce autoPin={true} />
          <FitView />
        </Graphin>
        {/* </KeepAlive> */}
      </ProCard>
    </VisualAnalysisLayout>
  );
};

export default MainGraph;
